import request from '@/utils/helper/request';
import ApiConfig from '@/config/api';
import { message } from 'ant-design-vue/es';
// 代理验证API地址
const apiValidator = {
    get(target, key) {
        if (key in target) {
            return target[key];
        } else {
            message.error('找不到对应的API地址');
        }
    }
};
const modelValidator = {
    get(target, key) {
        if (key in target) {
            return target[key];
        } else {
            message.error('找不到对应的API模块');
        }
    }
};

// 遍历配置文件
const finalApi = Object.keys(ApiConfig).reduce((finalApi, ModelKey) => {
    const Model = ApiConfig[ModelKey];
    const apis = Object.keys(Model).reduce((apis, apiKey) => {
        const api = Model[apiKey].trim().split('|'); // 去除空格并分割
        if (api.length !== 2 || !api[0]) {
            throw new Error(`${ModelKey}模块${apiKey}接口配置错误，`);
        } // 避免产生'|xx'或者'xx'的格式
        const method = api.shift();
        const url = api.shift();
        if (method.toLowerCase() === 'get' || method.toLowerCase() === 'delete') {
            apis[apiKey] = (data = {}) => {
                // console.log(data);
                return request[method](url, {
                    params: {
                        ...data
                    }
                });
            };
        } else {
            apis[apiKey] = (data = {}, ...args) => {
                // console.log(url, data);
                return request[method](url, data, ...args);
            };
        }
        return apis;
    }, {});
    // 找不到指定的api地址
    const proxyApis = new Proxy(apis, apiValidator);
    finalApi[ModelKey] = proxyApis;
    return finalApi;
}, {});
// 找不到指定的model类
const proxyFinalApi = new Proxy(finalApi, modelValidator);
export default proxyFinalApi;
